#include <cv.h>
#include <highgui.h>
#include <stdio.h>
#include <math.h>
#include "config.h"

static const char* wndimg   = "img"   ;
static const char* wndresult= "result";
static const char* wndtempl = "templ" ;
static const char* khepera = "khepera.png";

int test4(int argc, char** argv)
{
	int numImage;
	char nomTempl[40] ="";
	strcat(nomTempl, folder);
	strcat(nomTempl, khepera);
	IplImage* img;
	IplImage* result;
	IplImage* templ = cvLoadImage( nomTempl, 1 );
	if (!templ)
	{
		printf("<test4> Couldn't load %s\n", nomTempl );
		return -1;
	}
    cvNamedWindow( wndimg   , 1);
    cvNamedWindow( wndresult, 1);
    cvNamedWindow( wndtempl , 1);
	cvMoveWindow(wndimg   ,   0, 500);
	cvMoveWindow(wndresult, 500, 500);
	cvMoveWindow(wndtempl ,1000, 500);
    cvShowImage( wndtempl , templ );
	printf("<test4> : debut de la fonction\n");
    for( numImage = 0; names[numImage] != 0; numImage++ )
    {
		char nomImage[40] = "";
        int touche;
		float src_x;
		float src_y;
		int x;
		int y;
		CvPoint max_loc;
		CvPoint min_loc;
		double   min_val = 0;
		double   max_val = 0;
        //CvMemStorage* storage = cvCreateMemStorage(0);
        //CvSeq* circles;
        
		strcat(nomImage, folder);
		strcat(nomImage, names[numImage]);
    	img = cvLoadImage( nomImage, 1 );
        if( !img )
        {
            printf("<test4> Couldn't load %s\n", names[numImage] );
            continue;
        }
        printf("<test4> image %s chargée\n", names[numImage] );
        src_x = cvGetSize(img).width;
        src_y = cvGetSize(img).height;
        // pour éviter les exceptions : (output image should be (W - w + 1)x(H - h + 1))
        x = (int)src_x- cvGetSize(templ).width +1;
        y = (int)src_y - cvGetSize(templ).height +1;
        result = cvCreateImage(cvSize(x,y),IPL_DEPTH_32F,1);
        
        cvMatchTemplate( img, templ, result, CV_TM_CCOEFF_NORMED); //CV_TM_SQDIFF );
		max_loc = cvPoint(0,0);
		min_loc = cvPoint(0,0);
		cvMinMaxLoc(result, &min_val, &max_val, &min_loc, &max_loc, 0);
		
		printf("<test4> min_val = %f at pixel (%d;%d)\n", min_val, min_loc.x, min_loc.y);
		printf("<test4> max_val = %f at pixel (%d;%d)\n", max_val, max_loc.x, max_loc.y);
		
		cvCircle( img, cvPoint(min_loc.x + cvGetSize(templ).width /2,min_loc.y + cvGetSize(templ).height /2), 3, CV_RGB(0,255,0), -1, 8, 0 );
		cvCircle( img, cvPoint(max_loc.x + cvGetSize(templ).width /2,max_loc.y + cvGetSize(templ).height /2), 3, CV_RGB(255,0,0), -1, 8, 0 );

        cvShowImage( wndimg   , img   );
        cvShowImage( wndresult, result);
        touche = cvWaitKey(0);
		cvReleaseImage(&result);
		cvReleaseImage(&img   );
        if( (char)touche == 27 )
            break;
    }
    cvReleaseImage(&templ );
    cvDestroyWindow( wndimg   );
    cvDestroyWindow( wndresult);
    cvDestroyWindow( wndtempl );
    return 0;
}